﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Documents.DocumentStructures;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SportComplex.Model;
using SportComplex.Program.Pages.EditAddPages;

namespace SportComplex.Program.Pages
{
    /// <summary>
    /// Логика взаимодействия для View.xaml
    /// </summary>
    /// 


    public partial class View : Page
    {
        public View()
        {
            InitializeComponent();
            // Перекидываем имя пользователя
            NameUserLb.Content = GlobalVaribles.name_user;

            // Передача данных в ComboBox скидки
            FilterDiscountCmbx.Items.Add("Все");
            FilterDiscountCmbx.Items.Add("от 0 до 5%");
            FilterDiscountCmbx.Items.Add("от 5% до 15%");
            FilterDiscountCmbx.Items.Add("от 15% до 30%");
            FilterDiscountCmbx.Items.Add("от 30% до 70%");
            FilterDiscountCmbx.Items.Add("от 70% до 100%");

            // Передача данных в ComboBox для работы с таблицей "ТРЕНЕРЫ"
            //FilterTrainersSectionCbx.ItemsSource = Entities.GetContext().Trainers.ToList();
            //FilterTrainersSectionCbx.SelectedValuePath = "ID_section";
            //FilterTrainersSectionCbx.DisplayMemberPath = "lfname";

            // Загружаем все таблицы
            dGridSections.ItemsSource = Entities.GetContext().Section.ToList();
            dGridTrainers.ItemsSource = Entities.GetContext().Trainers.ToList();
            dGridTrainersForAdmin.ItemsSource = Entities.GetContext().Trainers.ToList();
            dGridEntryInSection.ItemsSource = Entities.GetContext().EntryInSection.ToList();
            dGridClients.ItemsSource = Entities.GetContext().Clients.ToList();

            // Выбор конфигурации в зависимости от пользователя
            switch (GlobalVaribles.type_user)
            {
                case -1: // гость
                    SwitchOnSectionTableBtn.IsEnabled = true;

                    NameUserLb.Background = System.Windows.Media.Brushes.Black;
                    NameUserLb.Foreground = System.Windows.Media.Brushes.White;
                    break;
                case 0:  // админ
                    SwitchOnClients.IsEnabled = true;
                    SwitchOnEntryInSectionTableBtn.IsEnabled = true;
                    SwitchOnSectionTableBtn.IsEnabled = true;
                    SwitchOnTrainersTableBtn.IsEnabled = true;

                    EditorEntryInSectionBtn.Visibility = Visibility.Visible;
                    EditorSectionBtn.Visibility = Visibility.Visible;
                    EditorTrainerBtn.Visibility = Visibility.Visible;

                    NameUserLb.Background = System.Windows.Media.Brushes.BlanchedAlmond;
                    NameUserLb.Foreground = System.Windows.Media.Brushes.Black;
                    break;

                case 1:  // тренер
                    SwitchOnClients.IsEnabled = true;
                    SwitchOnTrainersTableBtn.IsEnabled = true;
                    SwitchOnSectionTableBtn.IsEnabled = true;
                    SwitchOnEntryInSectionTableBtn.IsEnabled = true;

                    NameUserLb.Background = System.Windows.Media.Brushes.Beige;
                    NameUserLb.Foreground = System.Windows.Media.Brushes.Black;
                    break;

                case 2:  // клиент
                    SwitchOnSectionTableBtn.IsEnabled = true;
                    SwitchOnTrainersTableBtn.IsEnabled = true;

                    NameUserLb.Background = System.Windows.Media.Brushes.Azure;
                    NameUserLb.Foreground = System.Windows.Media.Brushes.Black;
                    break;
            }
        }

        // Вернуться на страницу входа
        private void backBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new ConnectMode());

            SwitchOnClients.IsEnabled = false;
            SwitchOnEntryInSectionTableBtn.IsEnabled = false;
            SwitchOnSectionTableBtn.IsEnabled = false;
            SwitchOnTrainersTableBtn.IsEnabled = false;

            EditorEntryInSectionBtn.Visibility = Visibility.Hidden;
            EditorSectionBtn.Visibility = Visibility.Hidden;
            EditorTrainerBtn.Visibility = Visibility.Hidden;
        }

        // Переключится в работу с таблицей "СЕКЦИИ"
        private void SwitchOnSectionTableBtn_Click(object sender, RoutedEventArgs e)
        {
            // Скрываем все ненужные элементы
            /* DataGrid */
            dGridClients.Visibility = Visibility.Hidden;
            dGridEntryInSection.Visibility = Visibility.Hidden;
            dGridTrainers.Visibility = Visibility.Hidden;
            dGridTrainersForAdmin.Visibility = Visibility.Hidden;
            /* AddButton */
            AddEntryBtn.Visibility = Visibility.Hidden;
            AddTrainerBtn.Visibility = Visibility.Hidden;
            /* DeleteButton */
            DeleteEntryBtn.Visibility = Visibility.Hidden;
            DeleteTrainerBtn.Visibility = Visibility.Hidden;
            DeleteClientBtn.Visibility = Visibility.Hidden;
            /* SearchTxb */
            SearchClientSP.Visibility = Visibility.Hidden;
            SearchTrainerSP.Visibility = Visibility.Hidden;
            /* ComboBox */
            FilterEntryClientSP.Visibility = Visibility.Hidden;
            FilterEntrySectionSP.Visibility = Visibility.Hidden;
            FilterEntryClientSP.Visibility = Visibility.Hidden;
            FilterEntryTrainerSP.Visibility = Visibility.Hidden;
            FilterTrainersSectionSP.Visibility = Visibility.Hidden;
            /* DatePicker */
            FilterEntryDateSP.Visibility = Visibility.Hidden;
            /* Labels */
            NumAllRecordsFromClientsTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromEntryTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromTrainersTable.Visibility = Visibility.Hidden;
            NumRecordsFromClientsDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromEntryDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromTrainersDataGrid.Visibility = Visibility.Hidden;

            // Отображаем нужные элементы для админа
            if (GlobalVaribles.type_user == 0)
            {
                dGridSections.Visibility = Visibility.Visible;
                SearchSectionSP.Visibility = Visibility.Visible;
                FilterDiscountSP.Visibility = Visibility.Visible;
                AddSectionBtn.Visibility = Visibility.Visible;
                DeleteSectionBtn.Visibility = Visibility.Visible;
                NumRecordsFromSectionDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromSectionDataGrid.Content = "Найдено записей (" + dGridSections.Items.Count.ToString() + ")";
                NumAllRecordsFromSectionTable.Visibility = Visibility.Visible;
                NumAllRecordsFromSectionTable.Content = "Записей в таблице (" + Entities.GetContext().Section.Count().ToString() + ")";

            }
            else // для остальных пользователей
            {
                dGridSections.Visibility = Visibility.Visible;
                SearchSectionSP.Visibility = Visibility.Visible;
                FilterDiscountSP.Visibility = Visibility.Visible;
                NumRecordsFromSectionDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromSectionDataGrid.Content = "Найдено записей (" + dGridSections.Items.Count.ToString() + ")";
                NumAllRecordsFromSectionTable.Visibility = Visibility.Visible;
                NumAllRecordsFromSectionTable.Content = "Записей в таблице (" + Entities.GetContext().Section.Count().ToString() + ")";
            }
        }

        // Переключится в работу с таблицей "ТРЕНЕРЫ"
        private void SwitchOnTrainersTableBtn_Click(object sender, RoutedEventArgs e)
        {
            // Скрываем все ненужные элементы
            /* DataGrid */
            dGridClients.Visibility = Visibility.Hidden;
            dGridEntryInSection.Visibility = Visibility.Hidden;
            dGridTrainersForAdmin.Visibility = Visibility.Hidden;
            dGridSections.Visibility = Visibility.Hidden;
            /* AddButton */
            AddEntryBtn.Visibility = Visibility.Hidden;
            AddSectionBtn.Visibility = Visibility.Hidden;
            /* DeleteButton */
            DeleteEntryBtn.Visibility = Visibility.Hidden;
            DeleteSectionBtn.Visibility = Visibility.Hidden;
            DeleteClientBtn.Visibility = Visibility.Hidden;
            /* SearchTxb */
            SearchClientSP.Visibility = Visibility.Hidden;
            SearchSectionSP.Visibility = Visibility.Hidden;
            /* ComboBox */
            FilterEntryTrainerSP.Visibility = Visibility.Hidden;
            FilterEntrySectionSP.Visibility = Visibility.Hidden;
            FilterDiscountSP.Visibility = Visibility.Hidden;
            FilterEntryClientSP.Visibility = Visibility.Hidden;
            /* DatePicker */
            FilterEntryDateSP.Visibility = Visibility.Hidden;
            /* Labels */
            NumAllRecordsFromSectionTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromClientsTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromEntryTable.Visibility = Visibility.Hidden;
            NumRecordsFromSectionDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromClientsDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromEntryDataGrid.Visibility = Visibility.Hidden;

            // Отображаем нужные элементы для админа
            if (GlobalVaribles.type_user == 0)
            {
                dGridTrainersForAdmin.Visibility = Visibility.Visible;
                SearchTrainerSP.Visibility = Visibility.Visible;
                //FilterTrainersSectionSP.Visibility = Visibility.Visible;
                AddTrainerBtn.Visibility = Visibility.Visible;
                DeleteTrainerBtn.Visibility = Visibility.Visible;
                NumRecordsFromTrainersDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromTrainersDataGrid.Content = "Найдено записей (" + dGridTrainers.Items.Count + ")";
                NumAllRecordsFromTrainersTable.Visibility = Visibility.Visible;
                NumAllRecordsFromTrainersTable.Content = "Записей в таблице (" + Entities.GetContext().Trainers.Count() + ")";
            }
            else // для остальных пользователей
            {
                dGridTrainers.Visibility = Visibility.Visible;
                SearchTrainerSP.Visibility = Visibility.Visible;
                //FilterTrainersSectionSP.Visibility = Visibility.Visible;
                NumRecordsFromTrainersDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromTrainersDataGrid.Content = "Найдено записей (" + dGridTrainers.Items.Count + ")";
                NumAllRecordsFromTrainersTable.Visibility = Visibility.Visible;
                NumAllRecordsFromTrainersTable.Content = "Записей в таблице (" + Entities.GetContext().Trainers.Count() + ")";
            }
        }

        // Переключится в работу с таблицей "ЗАПИСИ В СЕКЦИЮ"
        private void SwitchOnEntryInSectionTableBtn_Click(object sender, RoutedEventArgs e)
        {
            // Скрываем все ненужные элементы
            /* DataGrid */
            dGridClients.Visibility = Visibility.Hidden;
            dGridTrainers.Visibility = Visibility.Hidden;
            dGridTrainersForAdmin.Visibility = Visibility.Hidden;
            dGridSections.Visibility = Visibility.Hidden;
            /* AddButton */
            AddTrainerBtn.Visibility = Visibility.Hidden;
            AddSectionBtn.Visibility = Visibility.Hidden;
            /* DeleteButton */
            DeleteTrainerBtn.Visibility = Visibility.Hidden;
            DeleteSectionBtn.Visibility = Visibility.Hidden;
            DeleteClientBtn.Visibility = Visibility.Hidden;
            /* SearchTxb */
            SearchClientSP.Visibility = Visibility.Hidden;
            SearchTrainerSP.Visibility = Visibility.Hidden;
            SearchSectionSP.Visibility = Visibility.Hidden;
            /* Filter */
            FilterDiscountSP.Visibility = Visibility.Hidden;
            //FilterTrainersSectionSP.Visibility = Visibility.Hidden;
            /* Labels */
            NumAllRecordsFromSectionTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromClientsTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromTrainersTable.Visibility = Visibility.Hidden;
            NumRecordsFromSectionDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromClientsDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromTrainersDataGrid.Visibility = Visibility.Hidden;
            

            // Отображаем нужные элементы для админа
            if (GlobalVaribles.type_user == 0)
            {
                dGridEntryInSection.Visibility = Visibility.Visible;
                //FilterEntrySectionSP.Visibility = Visibility.Visible;
                //FilterEntryClientSP.Visibility = Visibility.Visible;
                //FilterEntryTrainerSP.Visibility = Visibility.Visible;
                //FilterEntryDateSP.Visibility = Visibility.Visible;
                AddEntryBtn.Visibility = Visibility.Visible;
                DeleteEntryBtn.Visibility = Visibility.Visible;
                NumRecordsFromEntryDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromEntryDataGrid.Content = "Найдено записей (" + dGridEntryInSection.Items.Count + ")";
                NumAllRecordsFromEntryTable.Visibility = Visibility.Visible;
                NumAllRecordsFromEntryTable.Content = "Записей в таблице (" + Entities.GetContext().EntryInSection.Count() + ")";
            }
            else // для остальных пользователей
            {
                dGridEntryInSection.Visibility = Visibility.Visible;
                //FilterEntrySectionSP.Visibility = Visibility.Visible;
                //FilterEntryClientSP.Visibility = Visibility.Visible;
                //FilterEntryTrainerSP.Visibility = Visibility.Visible;
                //FilterEntryDateSP.Visibility = Visibility.Visible;
                NumRecordsFromEntryDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromEntryDataGrid.Content = "Найдено записей (" + dGridEntryInSection.Items.Count + ")";
                NumAllRecordsFromEntryTable.Visibility = Visibility.Visible;
                NumAllRecordsFromEntryTable.Content = "Записей в таблице (" + Entities.GetContext().EntryInSection.Count() + ")";
            }
        }

        // Переключится в работу с таблицей "КЛИЕНТЫ"
        private void SwitchOnClients_Click(object sender, RoutedEventArgs e)
        {
            // Скрываем все ненужные элементы
            /* DataGrid */
            dGridEntryInSection.Visibility = Visibility.Hidden;
            dGridTrainers.Visibility = Visibility.Hidden;
            dGridTrainersForAdmin.Visibility = Visibility.Hidden;
            dGridSections.Visibility = Visibility.Hidden;
            /* AddButton */
            AddEntryBtn.Visibility = Visibility.Hidden;
            AddTrainerBtn.Visibility = Visibility.Hidden;
            AddSectionBtn.Visibility = Visibility.Hidden;
            /* DeleteButton */
            DeleteEntryBtn.Visibility = Visibility.Hidden;
            DeleteTrainerBtn.Visibility = Visibility.Hidden;
            DeleteSectionBtn.Visibility = Visibility.Hidden;
            /* SearchTxb */
            SearchTrainerSP.Visibility = Visibility.Hidden;
            SearchSectionSP.Visibility = Visibility.Hidden;
            /* ComboBox */
            FilterEntryTrainerSP.Visibility = Visibility.Hidden;
            FilterEntrySectionSP.Visibility = Visibility.Hidden;
            FilterDiscountSP.Visibility = Visibility.Hidden;
            FilterEntryClientSP.Visibility = Visibility.Hidden;
            FilterTrainersSectionSP.Visibility = Visibility.Hidden;
            /* DatePicker */
            FilterEntryDateSP.Visibility = Visibility.Hidden;
            /* Labels */
            NumAllRecordsFromSectionTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromEntryTable.Visibility = Visibility.Hidden;
            NumAllRecordsFromTrainersTable.Visibility = Visibility.Hidden;
            NumRecordsFromSectionDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromEntryDataGrid.Visibility = Visibility.Hidden;
            NumRecordsFromTrainersDataGrid.Visibility = Visibility.Hidden;

            // Отображаем нужные элементы для админа
            if (GlobalVaribles.type_user == 0)
            {
                dGridClients.Visibility = Visibility.Visible;
                SearchClientSP.Visibility = Visibility.Visible;
                DeleteClientBtn.Visibility = Visibility.Visible;
                NumRecordsFromClientsDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromClientsDataGrid.Content = "Найдено записей (" + dGridClients.Items.Count + ")";
                NumAllRecordsFromClientsTable.Visibility = Visibility.Visible;
                NumAllRecordsFromClientsTable.Content = "Записей в таблице (" + Entities.GetContext().Clients.Count() + ")";
            }
            else // для остальных пользователей
            {
                dGridClients.Visibility = Visibility.Visible;
                SearchClientSP.Visibility = Visibility.Visible;
                NumRecordsFromClientsDataGrid.Visibility = Visibility.Visible;
                NumRecordsFromClientsDataGrid.Content = "Найдено записей (" + dGridClients.Items.Count + ")";
                NumAllRecordsFromClientsTable.Visibility = Visibility.Visible;
                NumAllRecordsFromClientsTable.Content = "Записей в таблице (" + Entities.GetContext().Clients.Count() + ")";
            }
        }

        /** ФУНКЦИИ РАБОТЫ С ТАБЛИЦЕЙ СЕКЦИИ **/

        // Добавление новой секции
        private void AddSectionBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddSection(null));
        }

        // Удаление выделенной секции
        private void DeleteSectionBtn_Click(object sender, RoutedEventArgs e)
        {
            // Передача выбранного элемента из списка записей
            var seсtion_remove = dGridSections.SelectedItems.Cast<Model.Section>().ToList();
            var section_Remove = dGridSections.SelectedItem as Model.Section;

            if (seсtion_remove.Count != 0)
            {
                if (MessageBox.Show($"Вы точно хотите удалить секцию?",
                                     "Внимание", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try // Проверка на ссылочную целостность
                    {
                        var _exist = (from structEntry in Entities.GetContext().EntryInSection
                                      where structEntry.ID_section == section_Remove.ID_section
                                      select structEntry).First();

                        if (_exist != null)
                        {
                            MessageBox.Show("Секцию удалить нельзя!\nСуществует связь!", "Ошибка",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    catch
                    {
                        try
                        {
                            Entities.GetContext().Section.RemoveRange(seсtion_remove);
                            Entities.GetContext().SaveChanges();
                            dGridSections.ItemsSource = Entities.GetContext().Section.ToList();
                            NumRecordsFromSectionDataGrid.Content = "Найдено записей (" + dGridSections.Items.Count + ")";
                            MessageBox.Show("Данные удалены!");
                        }
                        catch (Exception ex)
                        { MessageBox.Show(ex.Message); }
                    }
                }
            }
            else MessageBox.Show("Сначала выберите секцию в списке!");
        }

        // Редактирование секции
        private void EditSectionBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddSection((sender as Button).DataContext as Model.Section)); 
        }

        // Поиск секции
        private void SearchSectionTxb_TextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateSection();
        }

        // Фильтрация скидки
        private void FilterDiscountCmbx_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateSection();
        }

        // Механизм одновременной работы поиска и фильтра для секции
        public void UpdateSection()
        {
            var sectionList = Entities.GetContext().Section.ToList();

            if (FilterDiscountCmbx.SelectedIndex == 1)
                sectionList = sectionList.Where(p => p.discount >= 0 && p.discount < 5).ToList();
            if (FilterDiscountCmbx.SelectedIndex == 2)
                sectionList = sectionList.Where(p => p.discount >= 5 && p.discount < 15).ToList();
            if (FilterDiscountCmbx.SelectedIndex == 3)
                sectionList = sectionList.Where(p => p.discount >= 15 && p.discount < 30).ToList();
            if (FilterDiscountCmbx.SelectedIndex == 4)
                sectionList = sectionList.Where(p => p.discount >= 30 && p.discount < 70).ToList();
            if (FilterDiscountCmbx.SelectedIndex == 5)
                sectionList = sectionList.Where(p => p.discount >= 70 && p.discount < 100).ToList();

            sectionList = sectionList.Where(p =>
                                            p.name.ToLower().Contains(SearchSectionTxb.Text.ToLower())).ToList();

            dGridSections.ItemsSource = sectionList.ToList();
            NumRecordsFromSectionDataGrid.Content = "Найдено записей (" + dGridSections.Items.Count + ")";
        }

        /** ФУНКЦИИ РАБОТЫ С ТАБЛИЦЕЙ "ТРЕНЕРЫ" **/

        // Добавление нового тренера
        private void AddTrainerBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddTrainers(null));
        }

        // Удаление тренера
        private void DeleteTrainerBtn_Click(object sender, RoutedEventArgs e)
        {
            // Передача выбранного элемента из списка записей
            var trainer_remove = dGridTrainersForAdmin.SelectedItems.Cast<Trainers>().ToList();
            var trainer_Remove = dGridTrainersForAdmin.SelectedItem as Trainers;

            if (trainer_remove.Count != 0)
            {
                if (MessageBox.Show($"Вы точно хотите удалить тренера?",
                                     "Внимание", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try // Проверка на ссылочную целостность
                    {
                        var _exist = (from structEntry in Entities.GetContext().EntryInSection
                                      where structEntry.ID_trainer == trainer_Remove.ID_trainer
                                      select structEntry).First();

                        if (_exist != null)
                        {
                            MessageBox.Show("Тренера удалить нельзя!\nСуществует запись с этим тренером!", "Ошибка",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    catch
                    {
                        try
                        {
                            Entities.GetContext().Trainers.RemoveRange(trainer_remove);
                            Entities.GetContext().SaveChanges();
                            dGridTrainers.ItemsSource = Entities.GetContext().Trainers.ToList();
                            dGridTrainersForAdmin.ItemsSource = Entities.GetContext().Trainers.ToList();
                            NumRecordsFromTrainersDataGrid.Content = "Найдено записей (" + dGridTrainers.Items.Count + ")";
                            MessageBox.Show("Данные удалены!");
                        }
                        catch (Exception ex)
                        { MessageBox.Show(ex.Message); }
                    }
                }
            }
            else MessageBox.Show("Сначала выберите тренера в списке!");
        }

        // Редактирование тренера
        private void EditTrainerBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddTrainers((sender as Button).DataContext as Trainers));
        }

        // Поиск тренера
        private void SearchTrainerTxb_TextChanged(object sender, TextChangedEventArgs e)
        {
            var trainerList = Entities.GetContext().Trainers.ToList();

            trainerList = trainerList.Where(p =>
                                            p.lfname.ToLower().Contains(SearchTrainerTxb.Text
                                                                        .ToLower()))
                                                                        .ToList();

            dGridTrainersForAdmin.ItemsSource = trainerList.ToList();
            dGridTrainers.ItemsSource = trainerList.ToList();

            NumRecordsFromTrainersDataGrid.Content = "Найдено записей (" + dGridTrainers.Items.Count + ")";
        }


        /** ФУНКЦИИ РАБОТЫ С ТАБЛИЦЕЙ "ЗАПИСИ НА СЕКЦИИ" **/

        // Редактирование
        private void EditEntyInSectionBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddEntryInSection((sender as Button).DataContext as EntryInSection));
        }

        // Добавление
        private void AddEntryBtn_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new EditAddEntryInSection(null));
        }

        // Удаление
        private void DeleteEntryBtn_Click(object sender, RoutedEventArgs e)
        {
            // Передача выбранного элемента из списка записей
            var entry_remove = dGridEntryInSection.SelectedItems.Cast<EntryInSection>().ToList();

            if (entry_remove.Count != 0)
            {
                if (MessageBox.Show($"Вы точно хотите удалить следующие {entry_remove.Count()} элементов?",
                                     "Внимание", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try
                    {
                        Entities.GetContext().EntryInSection.RemoveRange(entry_remove);
                        Entities.GetContext().SaveChanges();
                        dGridEntryInSection.ItemsSource = Entities.GetContext().EntryInSection.ToList();
                        NumRecordsFromEntryDataGrid.Content = "Найдено записей (" + dGridEntryInSection.Items.Count + ")";
                        MessageBox.Show("Данные удалены!");
                    }
                    catch (Exception ex)
                    { MessageBox.Show(ex.Message); }
                }
            }
            else MessageBox.Show("Сначала выберите элемент(ы) в списке!");
        }

        /** ФУНКЦИИ РАБОТЫ С ТАБЛИЦЕЙ "КЛИЕНТЫ" **/
        // Поиск клиента по ФИ
        private void SearchClientTxb_TextChanged(object sender, TextChangedEventArgs e)
        {
            var clientsList = Entities.GetContext().Clients.ToList();
            clientsList = clientsList.Where(p =>
                                            p.lfname.ToLower().Contains(SearchClientTxb.Text.ToLower())).ToList();

            dGridClients.ItemsSource = clientsList.ToList();
            NumRecordsFromClientsDataGrid.Content = "Найдено записей (" + dGridClients.Items.Count + ")";
        }

        // Удаление клиента
        private void DeleteClientBtn_Click(object sender, RoutedEventArgs e)
        {
            // Передача выбранного элемента из списка записей
            var client_remove = dGridClients.SelectedItems.Cast<Clients>().ToList();
            var client_Remove = dGridClients.SelectedItem as Clients;

            if (client_remove.Count != 0)
            {
                if (MessageBox.Show($"Вы точно хотите удалить клиента?",
                                     "Внимание", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                {
                    try // Проверка на ссылочную целостность данных
                    {
                        var _exist = (from structEntry in Entities.GetContext().EntryInSection
                                      where structEntry.ID_client == client_Remove.ID_client
                                      select structEntry).First();

                        if (_exist != null)
                        {
                            MessageBox.Show("Клиента удалить нельзя!\nСуществует запись с этим клиентом!", "Ошибка",
                                        MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    catch
                    {
                        try
                        {
                            Entities.GetContext().Clients.RemoveRange(client_remove);
                            Entities.GetContext().SaveChanges();
                            dGridClients.ItemsSource = Entities.GetContext().Clients.ToList();
                            NumRecordsFromClientsDataGrid.Content = "Найдено записей (" + dGridClients.Items.Count + ")";
                            MessageBox.Show("Данные удалены!");
                        }
                        catch (Exception ex)
                        { MessageBox.Show(ex.Message); }
                    }
                }
            }
            else MessageBox.Show("Сначала выберите клиента в списке!");
        }


    }
}
